<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    dialog-width="700px"
    :page-show="pageShow"
    @dialog-close="dialogClose"
  >
    <template #toolPanel />
    <template #searchPanel>
      <search-panel  @search="search" :show-search-button="true"  :url="urlpath" :showAddButton="false"
                     @importClick="importClick" labelWidth="100" :left="true"
                     :showExportDataButton="true" @exportData="exportCardOrder" :exportStock="true" @exportStock="exportStock"
                     :batchDelete="true" @batchDelete="batchDelete">
        <el-form-item label="运营商:" prop="operatoruid">
          <el-select v-model="filters.operatorname" filterable clearable placeholder="请选择运营商">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in operator"
              :key="item.operatoruid"
              :label="item.operatorname"
              :value="item.operatorname">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进货名称:">
          <el-input v-model="filters.upName" clearable style="width: 200px" placeholder="进货名称" />
        </el-form-item>
        <el-form-item label="进货折扣:">
          <el-input v-model="filters.upDiscount" clearable style="width: 200px" placeholder="进货折扣" />
        </el-form-item>
        <el-form-item label="销售名称:">
          <el-select v-model="filters.downName" clearable style="width: 200px;" filterable collapse-tags placeholder="请选择销售名称" >
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in usersDown"
              :key="item.user.useruuid"
              :label="item.user.username"
              :value="item.user.useruuid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售折扣:">
          <el-input v-model="filters.downDiscount" clearable style="width: 200px" placeholder="销售折扣" />
        </el-form-item>
        <el-form-item label="产品名称:">
          <el-input v-model="filters.name" clearable style="width: 200px" placeholder="产品名称" />
        </el-form-item>
        <el-form-item label="卡卷号码:">
          <el-input v-model="filters.cardNum" clearable style="width: 200px" placeholder="卡卷号码" />
        </el-form-item>
        <el-form-item label="面值:">
          <el-input v-model="filters.faceValue" clearable style="width: 200px" placeholder="面值" />
        </el-form-item>
        <el-form-item label="状态:">
          <el-select v-model="filters.status" clearable filterable style="width: 200px" placeholder="请选择状态">
            <el-option value="0" label="全部">全部</el-option>
            <el-option value="1" label="入库">入库</el-option>
            <el-option value="2" label="出库">出库</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导入人:">
          <el-select v-model="filters.imName" filterable clearable style="width: 200px" placeholder="请选择导入人">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in users"
              :key="item.useruuid"
              :label="item.username"
              :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导出人:">
          <el-select v-model="filters.exName" filterable style="width: 200px" clearable placeholder="请选择导出人">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in users"
              :key="item.useruuid"
              :label="item.username"
              :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间:">
          <el-date-picker type="datetime" clearable placeholder="开始时间" format="yyyy-MM-dd HH:mm:ss"   v-model="filters.startTime" style="width: 200px;"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间:">
          <el-date-picker type="datetime" clearable placeholder="结束时间" format="yyyy-MM-dd HH:mm:ss"   v-model="filters.endTime" style="width: 200px;"></el-date-picker>
        </el-form-item>
      </search-panel>
    </template>
    <template #contentPanel>
      <data-table
        :value="tableData"
        :total-count="totalCount"
        :has-action="true"
        :current="start"
        :isShowSelection="true"
        @selection-change="selsChange"
        :table-column-attributes="tableColumnAttributes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #action="{row}">
          <el-button size="small" round @click="deleteOrder(row)">删除</el-button>
        </template>
      </data-table>
    </template>

    <template #dialog>
      <el-form :model="form" :inline="true"  label-width="100px" ref="form">
        <el-form-item label="运营商:" prop="operatorname" >
          <el-select v-model="form.operatorname" filterable clearable placeholder="请选择运营商">
            <el-option
              v-for="item in operator"
              :key="item.operatoruid"
              :label="item.operatorname"
              :value="item.operatorname">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进货名称:" prop="upName">
          <el-input v-model="form.upName" clearable style="width: 200px" placeholder="进货名称" />
        </el-form-item>
        <el-form-item label="进货折扣:" prop="upDiscount">
          <el-input v-model="form.upDiscount" clearable style="width: 200px" placeholder="进货折扣" />
        </el-form-item>
        <el-form-item label="销售名称:" prop="downName">
          <el-select v-model="form.downName" clearable style="width: 200px;" filterable placeholder="请选择销售名称" >
            <el-option
              v-for="item in usersDown"
              :key="item.user.useruuid"
              :label="item.user.username"
              :value="item.user.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售折扣:" prop="downDiscount">
          <el-input v-model="form.downDiscount" clearable style="width: 200px" placeholder="销售折扣" />
        </el-form-item>
        <el-form-item>
          <el-row></el-row>
        </el-form-item>
        <el-form-item>
          <el-row>
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="headers"
              :limit="1"
              ref="upload"
              :on-remove="imageListRemove"
              :on-change="handleChange"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :auto-upload="false"
            >
              <el-button size="small" round type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传固定的xls/xlsx文件。您可以点击<a style="color: #3a8ee6;" :href="src">下载模板</a></div>
            </el-upload>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer el-dialog__footer" style="text-align: center;">
        <el-button size="small" round @click.native="dialogVisible = false">取消</el-button>
        <el-button size="small" round type="primary" @click.native="addSubmit">提交</el-button>
      </div>
<!--      <importExcel src="http://120.79.142.7:9999/kamimoban.xlsx" @operate="exportData" @cancel="onCancel"/>-->
    </template>

  </base-layout>
</template>

<script>
import baseMixin from '@/mixins/base'
// import DialogDataForm from './components/DialogDataForm'
import { getToken} from '@/utils/auth'
import { findPageCardOrder,deleteOrder,exportOrder,importOrder,findPageOperator,findAllBroad,findAllDownShopInfo } from '@/api/utilsapi'
import importExcel from '@/components/ImportExcel'
import moment from "moment";

export default {
  name: 'cardorder',
  components: { importExcel },
  mixins: [
    baseMixin({
      idName: 'id',
      findData: findPageCardOrder,
      format(res) {
        return res.map(data => {
          return data
        })
      }
    })
  ],
  data() {
    return {
      src:"http://120.79.142.7:9999/kamimoban.xlsx",
      pageShow: true,
      dialogData:{},
      headers: { 'x-auth-token': getToken() },
      uploadUrl: "",
      imageUrl: '',
      sels: [],//列表选中列
      fileList: [],
      dataList: [],
      tableColumnAttributes: [
        { name: '运营商名称', value: 'operatorname', width: 100 },
        { name: '进货名称', value: 'upName' },
        { name: '进货折扣', value: 'upDiscount' },
        { name: '销售名称', value: 'downName' },
        { name: '销售折扣', value: 'downDiscount' },
        { name: '产品名称', value: 'name' },
        { name: '卡卷号码', value: 'cardNum' },
        { name: '面值', value: 'faceValue' },
        { name: '导入人', value: 'imName' },
        { name: '导出人', value: 'exName' },
        { name: '过期时间', value: 'expireTime', width: 150 },
        { name: '状态', value: 'status' , formatter:this.formatStatus},
        { name: '创建时间', value: 'createTime', width: 150},
        { name: '导出时间', value: 'exTime', width: 150},
      ],
      urlpath:"http://",
      operator:[],
      users:[],
      usersDown:[],
      file:{},
      filters: {
        operatorname: '',
        startTime: moment().subtract('hour', 2).format('YYYY-MM-DD HH:mm:ss'),
        endTime:'',
        exName:'',
        imName:'',
        faceValue:'',
        status:'',
        cardNum:'',
        name:'',
        downDiscount:'',
        downName:'',
        upDiscount:'',
        upName:'',
        items:[]
      },
      form: {
        operatorname: '',
        exName:'',
        imName:'',
        faceValue:'',
        status:'',
        cardNum:'',
        name:'',
        downDiscount:'',
        downName:'',
        upDiscount:'',
        upName:'',
        items:[]
      }
    }
  },
  methods: {
    search(form){
      let para = {
        start: this.start,
        pageSize: this.pageSize,
        operatorname: this.filters.operatorname
      };
      para = this.filters;
      para.startTime = (this.filters.startTime == "" || this.filters.startTime == undefined) ? "" : moment(this.filters.startTime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss');
      para.endTime = (this.filters.endTime == "" || this.filters.endTime == undefined) ? "" : moment(this.filters.endTime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss');

      this.searchOptions = para;
      this.setTableData()
    },
    formatStatus: function (row, column) {
      return row.status == "1" ? '入库' : row.status == "2" ? '出库' : '未知';
    },
    deleteOrder(row) {
      this.$confirm('确认删除提交吗？', '提示', {roundButton:true}).then(() => {
        let para = row
        deleteOrder(para).then((res) => {
          this.resultSuccess(res)
        });
      });
    },
    //新增
    addSubmit: function () {
        this.$confirm('确认提交吗？', '提示', {roundButton:true}).then(() => {
          let para = this.dataList;
          importOrder(para).then((datas) => {
            this.resultSuccess(datas)
          }).catch(function (error) {
            console.log(error);
          });
        });
    },
    exportData(data) {
      this.dialogVisible = false
      data.forEach(item => {
        console.log(item)
        var temp = true
        this.filters.items.forEach((value, index, arr) => {
          // 判断条码号和芯片号是否重复
          if (item.barCode === value.barCode) {
            temp = false
          }
          if (item.serialNumber === value.serialNumber && (value.serialNumber != '' && value.serialNumber != null)){
            temp = false
            this.$message({message: 'xx',type: 'error'})
          }
        })
        if (temp) {
          this.filters.items.push(item)
        }
      })
    },
    onCancel() {
      this.dialogVisible = false
    },
    importClick() {
      this.dialogTitle = "导入"
      this.dialogVisible = true
    },
    findPageOperator(){
      let para = {
        start: 1,
        pageSize:101,
        operatorname:'',
      };
      findPageOperator(para).then((datas) => {
        let { message, code, data } = datas;
        if (code !== "0") {
          this.showMsg(message,'error')
        } else if(data && data.result){
          this.operator = data.result;
        }
      });
    },
    findAllBroad(){
      let para = {
        useruuid:'',
      };
      findAllBroad(para).then((datas) => {
        let { message, code, data } = datas;
        if (code !== "0") {
          this.showMsg(message,'error')
        } else if(data && data){
          this.users = data;
        }
      });
    },
    async findAllDownShopInfo(){
      let para = {useruuid: this.$store.getters.useruuid};
      const result = await findAllDownShopInfo(para);
      if(result.data){
        this.usersDown = result.data;
      }
    },
    imageListRemove(file, fileList) {
      this.fileList.splice(0, 1)
      this.dataList = []
    },
    handleExceed(files, fileList){
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleChange(file, fileList) {
      this.fileTemp = file.raw
      if (this.fileTemp) {
        if ((this.fileTemp.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
          || (this.fileTemp.type === 'application/vnd.ms-excel')) {
          this.importfxx(this.fileTemp)
        } else {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    importfxx(obj) {
      let _this = this
      let inputDOM = this.$refs.inputer
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0]
      var rABS = false // 是否将文件读取为二进制字符串
      var f = this.file
      var reader = new FileReader()
      // if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = ''
        var rABS = false // 是否将文件读取为二进制字符串
        var pt = this
        var wb // 读取完成的数据
        var outdata;
        var reader = new FileReader()

        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result)
          var length = bytes.byteLength
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          var XLSX = require('xlsx')
          if(rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), { // 手动转化
              type: 'base64'
            })
          } else {
            wb = XLSX.read(binary, {
              type: 'binary'
            })
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])// outdata就是你想要的东西
          this.da = [...outdata]
          if (_this.default) {
            _this.dataList = outdata
          } else {
            _this.importForm(outdata)
          }
        }
        reader.readAsArrayBuffer(f)
      }
      if (rABS) {
        reader.readAsArrayBuffer(f)
      } else {
        reader.readAsBinaryString(f)
      }
    },
    importForm(outdata) {
      this.dataList = []
      var isTrue = true
      outdata.forEach((value, index, arr) => {
        if (value['卡券号'] == null || value['卡券号'] == 'undefined') {
          this.$message({
            message: '第' + (index + 2) + '行，卡券号不能为空，请删除后重新上传！',
            type: 'error'
          })
          isTrue = false
        }
        const numbers = value['产品名称'].match(/\d+/g);
        if(numbers.length > 1){
          this.$message({
            message: '第' + (index + 2) + '行名称中金额不正确，请删除后重新上传！',
            type: 'error'
          })
          isTrue = false
        }
        if (value['密码'] == null || value['密码'] == 'undefined' || value['密码'] == "" ) {
          this.$message({
            message: '第' + (index + 2) + '行，密码不能为空，请删除后重新上传！',
            type: 'error'
          })
          isTrue = false
        }
      })
      if (isTrue) {
        outdata.forEach((value, index, arr) => {
          var show = {};
          show.name = value['产品名称']
          //提取面值
          const numbers = show.name.match(/\d+/g);
          show.faceValue = numbers[0];
          show.cardNum = value['卡券号']
          show.passwd = value['密码']
          show.expireTime = value['卡券过期时间']
          show.operatorname = this.form.operatorname;
          show.downDiscount = this.form.downDiscount;
          show.downName = this.form.downName;
          show.upName = this.form.upName;
          show.upDiscount = this.form.upDiscount;
          show.status = "1";
          this.dataList.push(show)
        })
        this.$message({
          message: '请耐心等待导入成功',
          type: 'success'
        })
      }
    },
    exportCardOrder(type){
      let para = {
        operatorname: this.filters.operatorname,
        pageSize: 10000,
      };
      para = this.filters;
      para.type = type ? type : "";
      para.startTime = (this.filters.startTime == "" || this.filters.startTime == undefined) ? "" : moment(this.filters.startTime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss');
      para.endTime = (this.filters.endTime == "" || this.filters.endTime == undefined) ? "" : moment(this.filters.endTime,"YYYY-MM-DD HH:mm:ss").format('YYYY-MM-DD HH:mm:ss');
      exportOrder(para).then(res => {
        let {message, code, data} = res;
        if (code !== "0") {
          this.showMsg(message,"error");
        } else {
          if(data.path){
            window.open(data.path);
          }
        }
      });
    },
    exportStock(){
      //出库
      this.$confirm('确认出库提交吗？出库后卡密状态将变更为出库,请谨慎操作', '提示', {roundButton:true}).then(() => {
        this.exportCardOrder("out");
      });
    },
    batchDelete(){
      if(this.sels.length == 0){
        this.$message({
          type: 'warning',
          message: '选择卡密！'
        })
        return ;
      }
      this.$confirm('确认删除提交吗？,请谨慎操作', '提示', {roundButton:true}).then(() => {
        for(var i = 0 ; i < this.sels.length;i++){
          let para = this.sels[i];
          deleteOrder(para).then((res) => {
          });
          this.resultSuccess(res)
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
  },
  mounted() {
    this.findPageOperator();
    this.findAllBroad();
    this.findAllDownShopInfo();
  }
}
</script>
